package handler

import (
	"context"
	"github.com/gin-gonic/gin"
	"net/http"
	"shopping-order/api/request"
	"shopping-order/global"
	"shopping-order/internal/dao"
	"shopping-order/internal/model"
	"time"
)

func AddOrder(c *gin.Context) {
	var req request.AddOrderForm
	var order model.Order
	var user model.User

	if req.UserId == 0 || req.Price == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "验证失败",
			"data": nil,
		})
		return
	}

	err := dao.GetOneByFile(&model.User{Id: uint32(req.UserId)}, &user)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "验证失败",
			"data": nil,
		})
		return
	}

	order = model.Order{
		UserId: req.UserId,
		Price:  req.Price,
	}

	dao.AddFile(&order)

	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "订单生成成功",
		"data": order.Id,
	})
}

func ListOrder(c *gin.Context) {
	var req request.ListOrderForm
	var order []model.Order

	if req.Status == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "验证失败",
			"data": nil,
		})
		return
	}

	err := dao.GetListByFile(&model.Order{Status: req.Status}, &order)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "查询失败",
			"data": false,
		})
		return
	}

	if req.Status == 3 {
		global.RDB.Set(context.Background(), "orderNum", len(order), time.Hour*24)
	}

	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "列表查询成功",
		"data": order,
	})

}

func ListByUserOrder(c *gin.Context) {
	var req request.ListByUserOrderForm
	var order []model.Order

	if req.UserId == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "验证失败",
			"data": nil,
		})
		return
	}

	err := dao.GetListByFile(&model.Order{UserId: req.UserId}, &order)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "查询失败",
			"data": false,
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "列表查询成功",
		"data": order,
	})
}
